package com.oazon.moco.playlist.db;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.provider.ContactsContract.Data;
import android.util.Log;

import com.oazon.moco.playlist.bean.ResourceBean;
import com.oazon.common.TaskHelper;
import com.oazon.common.util.SDcradUtil;

public class ResourceDao {
	
	private static final String TAG ="ResourceDao";
	
	private SQLiteDatabase db;

	// 单位MB
	private static final int SD_FREE_SIZE = 20;

	private static final String TABLE_NAME_RESOURCE = "resource";

	private static final String RESOURCE_ID = "id";
	private static final String RESOURCE_NET_URL = "net_url";
	private static final String RESOURCE_FILE_PATH = "file_path";
	private static final String RESOURCE_CREAT_TIME = "creat_time";
	private static final String RESOURCE_LIFE_TIME = "life_time";

	private static final Map<String, String> imageUrlAndPath = new HashMap<String, String>();
	private List<ResourceBean> beans;

	public ResourceDao(Context context) {
		MocoDB resourceDB = new MocoDB(context);
		db = resourceDB.getReadableDatabase();
		TaskHelper.exec(new Runnable() {

			@Override
			public void run() {
				beans = getAll();
				for (ResourceBean resourceBean : beans) {
					imageUrlAndPath.put(resourceBean.getNetUrl(),
							resourceBean.getFilePath());
				}
			}
		});
	}

	public long insertIntoResource(String netUrl, String filePath,
			String lifeTime) {
		Log.d(TAG, "===" + filePath);
		checkoutResource();
		// 查出是否已经存在这条记录了，如果存在就先删除
		if (getFilePathByUrl(netUrl) != null) {
			deleteByUrl(netUrl);
		}

		ContentValues values = new ContentValues();
		String time = new Date().toString(); 

		values.put(RESOURCE_NET_URL, netUrl);
		values.put(RESOURCE_FILE_PATH, filePath);
		values.put(RESOURCE_CREAT_TIME, time);
		values.put(RESOURCE_LIFE_TIME, lifeTime);

		imageUrlAndPath.put(netUrl, filePath);

		return db.insert(TABLE_NAME_RESOURCE, "", values);
	}

	/**
	 * 删除数据库和该图片
	 * 
	 * @param netUrl
	 * @return
	 */
	public int deleteByUrl(String netUrl) {
		deleteBitmapSD(netUrl);
		imageUrlAndPath.remove(netUrl);
		return db.delete(TABLE_NAME_RESOURCE, RESOURCE_NET_URL + "=?",
				new String[] { netUrl });
	}

	/**
	 * 根据媒体url获得媒体本地路径
	 * 
	 * @param netUrl
	 * @return null为不存在
	 */
	public String getFilePathByUrl(String netUrl) {
		String filePath = null;
		/*
		 * Cursor cursor = null; try { cursor = db.query(TABLE_NAME_RESOURCE,
		 * new String[] { RESOURCE_FILE_PATH }, RESOURCE_NET_URL + "=?", new
		 * String[] { netUrl }, null, null, null);
		 * 
		 * while (cursor.moveToNext()) { filePath = cursor.getString(cursor
		 * .getColumnIndex(RESOURCE_FILE_PATH)); } cursor.close(); } catch
		 * (Exception e) { if (cursor != null) { cursor.close(); } }
		 */
		filePath = imageUrlAndPath.get(netUrl);
		return filePath;
	}

	public String getNetUrlByFilePath(String filePath) {
		return imageUrlAndPath.get(filePath);
	}

	/**
	 * 当sd卡容量小于20M的时候删除多余图片
	 */
	@SuppressWarnings("deprecation")
	private void checkoutResource() {
		if (SDcradUtil.ExistSDCard() && beans != null) {
			for (ResourceBean resourceBean : beans) {
				if (new Date().getTime()
						- Date.parse(resourceBean.getCreatTime()) > Long
							.parseLong(resourceBean.getLifeTime())) {
					deleteByUrl(resourceBean.getNetUrl());
				}
			}
			while (SDcradUtil.getSDFreeSize() <= SD_FREE_SIZE) {
				if (beans.size() <= 0) {
					return;
				}
				deleteByUrl(beans.get(0).getNetUrl());
				beans.remove(0);
			}
		}
	}

	public ArrayList<ResourceBean> getAll() {
		ArrayList<ResourceBean> resourceBeans = new ArrayList<ResourceBean>();
		Cursor cursor = db.query(TABLE_NAME_RESOURCE, null, null, null, null,
				null, RESOURCE_CREAT_TIME, null);
		while (cursor.moveToNext()) {
			ResourceBean resourceBean = new ResourceBean();

			resourceBean
					.setId(cursor.getInt(cursor.getColumnIndex(RESOURCE_ID)));
			resourceBean.setNetUrl(cursor.getString(cursor
					.getColumnIndex(RESOURCE_NET_URL)));
			resourceBean.setFilePath(cursor.getString(cursor
					.getColumnIndex(RESOURCE_FILE_PATH)));
			resourceBean.setCreatTime(cursor.getString(cursor
					.getColumnIndex(RESOURCE_CREAT_TIME)));
			resourceBean.setLifeTime(cursor.getString(cursor
					.getColumnIndex(RESOURCE_LIFE_TIME)));

			resourceBeans.add(resourceBean);
		}
		cursor.close();
		return resourceBeans;
	}

	/**
	 * 将图片保存到sd卡中
	 * 
	 * @param bitmap
	 * @param path
	 * @return
	 */
	public String saveBitmapSD(Bitmap bitmap, String path) {

		// Date date = new Date();

		// String fileName = String.valueOf(date.getTime()) + ".png";
		// path = path + "/" + fileName;
		File file = new File(path);

		if (file.exists()) {
			file.delete();
		}
		try {
			file.createNewFile();
			FileOutputStream fileOutputStream = new FileOutputStream(file);

			if (bitmap.compress(Bitmap.CompressFormat.PNG, 100,
					fileOutputStream)) {
				Log.d(TAG, "compress");
				fileOutputStream.flush();
				fileOutputStream.close();
			}
		} catch (Exception e1) {
			Log.d(TAG, e1.toString() + "===" + bitmap.getWidth());
			e1.printStackTrace();
		}
		Log.d(TAG, path);
		return path;
	}

	/**
	 * 删除sd卡中图片
	 * 
	 * @param url
	 */
	public void deleteBitmapSD(String url) {
		File file = null;
		String path = getFilePathByUrl(url);
		if (path != null) {
			file = new File(path);
		}

		if (file != null) {
			file.deleteOnExit();
		}
	}

}
